/*
 * Copyright (C), 2002-2018, Caljm有限公司
 * FileName: EchoClientHandler
 * Author:   Byron Wang
 * Date:     2018/10/29 下午11:20
 * Description: //模块目的、功能描述
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */

package com.cpcs.delimiter;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 功能描述：
 *
 * @author Byron Wang
 * @since 2018/10/29
 */
public class EchoClientHandler extends SimpleChannelInboundHandler<Object> {

    private int counter;

    private final byte[] request;

    public EchoClientHandler() {
        request = "QueryTime$_".getBytes();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 使用了 DelimiterBasedFrameDecoder 之后的代码
        String body = (String) msg;
        System.out.println("Receive message: " + body + ", COUNTER: " + (++counter));
//        ctx.channel().closeFuture().sync(); // 接收服务端响应后关闭连接
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf message;

        for (int i = 0; i < 100; i++) {
            message = Unpooled.buffer(request.length);
            message.writeBytes(request);
            ctx.writeAndFlush(message);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }


}
